from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import pymysql

from user.user import User


class MyPool:
    pool = None

    def __init__(self):
        # 创建数据库引擎
        self.engine = create_engine(
            'mysql+pymysql://root:1VC~V%40YzG1y~df&@111.229.32.62/liyuexiuxian',
            pool_size=10,  # 最大连接数
            max_overflow=20,  # 超过连接池大小外最多创建的连接
            pool_recycle=3600,  # 连接池中的连接最大存活时间
            pool_pre_ping=True  # 连接池中的连接在使用前进行测试
        )
        # 创建 SessionFactory
        self.session = sessionmaker(bind=self.engine)

    def add_user(self, user_id, name):
        session = self.session()
        try:
            new_user = User(user_id=user_id, name=name)
            session.add(new_user)
            session.commit()
            # 获取新插入记录的信息
            inserted_user = session.query(User).filter_by(user_id=user_id).first()
            return inserted_user
        except Exception as e:
            session.rollback()
            raise e
        finally:
            session.close()
